package com.test.common.entity.perf;

import com.test.common.enums.perf.PerfScriptPlatformEnum;
import lombok.Data;

import javax.persistence.*;
import java.util.Date;
import java.util.List;

@Data
@Entity
@Table(name = "t_perf_script", uniqueConstraints = @UniqueConstraint(columnNames = "objectId"))
public class PerfScriptEntity {

    public PerfScriptEntity() {
    }

    public PerfScriptEntity(String name, String creator, String objectId, PerfScriptPlatformEnum platform, long size) {
        this();
        this.name = name;
        this.creator = creator;
        this.platform = platform;
        this.objectId = objectId;
        this.createTime = new Date();
        this.modifyTime = new Date();
        this.size = size;
    }

    public PerfScriptEntity(int id, String name, String creator, String objectId, PerfScriptPlatformEnum platform, long size) {
        this.id = id;
        this.name = name;
        this.creator = creator;
        this.objectId = objectId;
        this.platform = platform;
        this.modifyTime = new Date();
        this.size = size;
    }

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private int id;

    @Column(columnDefinition = "VARCHAR(65) NOT NULL DEFAULT '' COMMENT '任务名称' ")
    private String name;

    @Column(columnDefinition = "VARCHAR(32) NOT NULL DEFAULT 'TODO' COMMENT '任务创建人，如：张三'")
    private String creator;

    @Column(columnDefinition = "VARCHAR(32) NOT NULL COMMENT '资源 Mongo ID'")
    private String objectId;

    @Enumerated
    private PerfScriptPlatformEnum platform;

    @Access(value = AccessType.PROPERTY)
    @ManyToMany(cascade = {CascadeType.ALL}, fetch = FetchType.EAGER)
    @JoinTable(name = "t_perf_script_resources", joinColumns = {@JoinColumn(name = "script_id", referencedColumnName = "id")}, inverseJoinColumns = {@JoinColumn(name = "resource_id", referencedColumnName = "id")})
    private List<PerfResourceEntity> resources;

    @Transient
    private int[] resourceIds;

    @Column(columnDefinition = "DATETIME NOT NULL ON UPDATE CURRENT_TIMESTAMP COMMENT '任务创建时间'")
    private Date createTime = new Date();

    @Column(columnDefinition = "DATETIME NOT NULL ON UPDATE CURRENT_TIMESTAMP COMMENT '任务修改时间'")
    private Date modifyTime = new Date();

    @Column(columnDefinition = "int(11) NOT NULL COMMENT '文件大小 KB'")
    private long size;

    @Transient
    private String content;

//    public void setResources(List<PerfResourceEntity> resources) {
//        this.resources = resources;
//        this.resourceIds = new int[this.resources.size()];
//        for (int i = 0; i < this.resources.size(); i++) {
//            this.resourceIds[i] = this.resources.get(i).getId();
//        }
//    }

    public int[] getResourceIds() {
        this.resourceIds = new int[this.resources.size()];
        for (int i = 0; i < this.resources.size(); i++) {
            this.resourceIds[i] = this.resources.get(i).getId();
        }
        return this.resourceIds;
    }
}
